app.controller('sys_regionEditController', ['$scope', 'httpWrapService', 'dialogs', '$state', '$stateParams',
                        '$location', '$anchorScroll','AlertFactory','validationService',
            function ($scope, httpWrapService, dialogs, $state, $stateParams, $location, $anchorScroll, AlertFactory,validationService) {
    $scope.entity = {};
    $scope.tree = {};

    $scope.id = $stateParams.id;
    $scope.type = $stateParams.type || 'add';
    $scope.Alert = AlertFactory.newInstance();
    $scope.entity.parentId = $stateParams.parentId ? $stateParams.parentId : null;


    httpWrapService.post("system/region/listAll.do", {}).then(function(res){
	    $scope.data = res.data.data;
	    $scope.initSelected();
    });
    
    $scope.initSelected = function(){
    	if(!$scope.entity || !$scope.data || !$scope.entity.parentId) return;
    	for(var index in $scope.data) {
    		var row = $scope.data[index];
    		if($scope.entity.parentId == row.id) {
    			$scope.tree.obj = row;
    			break;
    		}
    	}
    }
    
    if($scope.id) {
        httpWrapService.post('system/region/view/' + $scope.id + '.do').then(function (res) {
            $scope.entity = res.data.entity;
            $scope.type = 'update';
            if($scope.entity && $scope.entity.parentId){
            	$scope.initSelected();
            }
        });
    }
    
	$scope.setting = {
	}
	
	$scope.$watch('tree.obj', function(newValue,oldValue){
		if(newValue && newValue.id){
			$scope.entity.parentId = newValue.id;
		}
	});
    


    $scope.unique = function(value){
        return validationService.unique({
            entityName : "common.rbac.po.Region",
            field : "code",
            value : value,
            id : $scope.id
        })
    }

    $scope.save = function () {
        httpWrapService.defaultSave( 'system/region/' + $scope.type + '.do',{
            entity : $scope.entity
        }, $scope).then(function (res) {
            $state.go('app.system.region.list');
        });

        // 保存成功返回列表页面

    }

    $scope.canle = function () {
        // 后退到列表页面
        $state.go('app.system.region.list');
    }
    

}]);